// 在main.js的最顶部（解析参数前）添加
console.log('main.js full argv:', process.argv);

const { app, BrowserWindow, ipcMain, screen, Menu, globalShortcut } = require('electron');
const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');

let mainWindow;
const settingsPath = path.join(app.getPath('userData'), 'overlay-settings.json');
function loadSettings() {
    try {
        if (fs.existsSync(settingsPath)) {
            const raw = fs.readFileSync(settingsPath, 'utf8');
            const saved = JSON.parse(raw);
            // 兼容旧配置（如果旧配置没有apiPort，自动添加默认值）
            return { ...saved, apiPort: saved.apiPort ?? 8989 };
        }
    } catch { }
    // 默认设置：深色模式，主题色#000
    console.log("load_setting")
    return {
        opacity: 1,
        width: 520,
        height: 480,
        x: 5,
        y: 5,
        alwaysOnTop: true,
        themeMode: 'dark',
        themeColor: '#000000',
        apiPort: 8989 // 新增端口配置，默认8989 
    };
}
function saveSettings(s) {
    try { fs.writeFileSync(settingsPath, JSON.stringify(s, null, 2), 'utf8'); } catch { }
}

let overlaySettings = loadSettings();

function createWindow() {
    // 禁用菜单栏
    Menu.setApplicationMenu(null);

    // 获取屏幕信息
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.workAreaSize;

    // 确保窗口在屏幕范围内
    const windowX = Math.max(0, Math.min(overlaySettings.x, width - overlaySettings.width));
    const windowY = Math.max(0, Math.min(overlaySettings.y, height - overlaySettings.height));

    // 创建悬浮窗
    mainWindow = new BrowserWindow({
        width: overlaySettings.width,
        height: overlaySettings.height,
        x: windowX,
        y: windowY,
        title: '小红猫DPS_v2.3.12', // 设置窗口标题
        icon: path.join(__dirname, '..', 'redcat.ico'), // 设置应用图标
        frame: false, // 无边框
        transparent: true, // 透明背景
        alwaysOnTop: overlaySettings.alwaysOnTop, // 置顶
        skipTaskbar: false, // 在任务栏显示，方便调试
        resizable: true, // 可调整大小
        show: false, // 先不显示，等加载完成再显示
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: false,
            webSecurity: false,
            backgroundThrottling: false, // 防止后台节流
            focusable: true, // 确保窗口可以获得焦点
            acceptFirstMouse: true // 允许第一次鼠标点击时获得焦点
        }
    });

    // 页面加载完成后显示窗口
    mainWindow.once('ready-to-show', () => {
        console.log('Window ready to show');
        // mainWindow.webContents.openDevTools({
        //     mode: 'detach' // 独立窗口显示，避免被悬浮窗遮挡
        // });

        // 强制显示窗口
        mainWindow.show();
        mainWindow.setOpacity(overlaySettings.opacity);

        // 确保窗口在屏幕中央可见
        const bounds = mainWindow.getBounds();
        console.log('Window bounds:', bounds);

        // 如果窗口在屏幕外，重新定位到屏幕中央
        const display = screen.getPrimaryDisplay();
        const centerX = Math.round((display.bounds.width - bounds.width) / 2);
        const centerY = Math.round((display.bounds.height - bounds.height) / 2);

        if (bounds.x < 0 || bounds.y < 0 ||
            bounds.x > display.bounds.width || bounds.y > display.bounds.height) {
            console.log('Window is outside screen bounds, repositioning to center');
            mainWindow.setPosition(centerX, centerY);
        }

        // 确保窗口可见并始终置顶
        mainWindow.focus();
        mainWindow.moveTop();
        mainWindow.setAlwaysOnTop(true, 'screen-saver');

        // 强制窗口到前台
        mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
        mainWindow.setFullScreenable(false);

        // 添加延迟确保窗口真正显示
        setTimeout(() => {
            mainWindow.focus();
            mainWindow.moveTop();
            console.log('Window final position:', mainWindow.getBounds());
            console.log('Window visible:', mainWindow.isVisible());
            console.log('Window minimized:', mainWindow.isMinimized());
        }, 1000);

        // 打开开发者工具（调试模式或显示问题时）
        if (process.argv.includes('--debug') || process.argv.includes('--show')) {
            mainWindow.webContents.openDevTools();
            console.log('Developer tools opened for debugging');
        }

        console.log('Floating overlay window displayed and positioned');
    });

    // 定期确保窗口置顶（防止被游戏覆盖）
    let alwaysOnTopPauseUntil = 0;
    let alwaysOnTopHardPaused = false;
    setInterval(() => {
        if (!mainWindow || mainWindow.isDestroyed()) return;
        // 若被临时，则跳过本次置顶
        if (alwaysOnTopHardPaused || Date.now() < alwaysOnTopPauseUntil) return;
        if (overlaySettings.alwaysOnTop) {
            // 使用最高级别的置顶
            mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
            mainWindow.moveTop();
            // 强制刷新窗口层级
            if (process.platform === 'win32') {
                mainWindow.setVisibleOnAllWorkspaces(true);
                mainWindow.setVisibleOnAllWorkspaces(false);
            }
        }
    }, 2000); // 每2秒检查一次

    // 加载悬浮窗页面
    mainWindow.loadFile('overlay.html').then(() => {
        console.log('HTML file loaded successfully');

        // 注册全局快捷键
        registerGlobalShortcuts();
    }).catch((error) => {
        console.error('Failed to load HTML file:', error);
    });

    // 调试模式下打开开发者工具
    if (process.argv.includes('--debug') || process.env.NODE_ENV === 'development') {
        mainWindow.webContents.openDevTools();
    }

    // 添加错误处理
    mainWindow.webContents.on('crashed', () => {
        console.error('Window crashed');
    });

    mainWindow.webContents.on('unresponsive', () => {
        console.error('Window unresponsive');
    });

    // 当窗口获得焦点时确保置顶
    mainWindow.on('focus', () => {
        if (overlaySettings.alwaysOnTop) {
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.moveTop();
        }
    });

    // 当窗口被点击时确保置顶
    mainWindow.webContents.on('before-input-event', (event, input) => {
        if (input.type === 'mouseDown' && overlaySettings.alwaysOnTop) {
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.moveTop();
        }
    });

    // 保存窗口位置和大小
    mainWindow.on('moved', () => {
        const [x, y] = mainWindow.getPosition();
        overlaySettings.x = x;
        overlaySettings.y = y;
    });

    mainWindow.on('resized', () => {
        const [width, height] = mainWindow.getSize();
        overlaySettings.width = width;
        overlaySettings.height = height;
    });

    // 窗口关闭时的处理
    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

const args = process.argv;
const portArgIndex = args.findIndex(arg => arg === '--port');
if (portArgIndex !== -1 && args[portArgIndex + 1]) {
    const port = parseInt(args[portArgIndex + 1]);
    if (!isNaN(port) && port > 0 && port < 65536) {
        overlaySettings.apiPort = port; // 覆盖配置中的端口
        console.log(`port args :${port}`);
    }
} else {
    console.log(`no port args`)
}


// 应用准备就绪时创建窗口
app.whenReady().then(() => {
    console.log('Electron app ready, creating window...');
    createWindow();
}).catch((error) => {
    console.error('Failed to start app:', error);
});

// 当所有窗口都被关闭时退出应用（macOS除外）
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// IPC 通信处理
ipcMain.handle('get-settings', () => {
    return overlaySettings;
});

ipcMain.handle('update-settings', (event, newSettings) => {
    overlaySettings = { ...overlaySettings, ...newSettings };
    saveSettings(overlaySettings);

    // 应用设置
    if (mainWindow) {
        if (newSettings.opacity !== undefined) {
            mainWindow.setOpacity(newSettings.opacity);
        }

        if (newSettings.width !== undefined || newSettings.height !== undefined) {
            mainWindow.setSize(
                newSettings.width || overlaySettings.width,
                newSettings.height || overlaySettings.height
            );
        }

        if (newSettings.x !== undefined || newSettings.y !== undefined) {
            mainWindow.setPosition(
                newSettings.x || overlaySettings.x,
                newSettings.y || overlaySettings.y
            );
        }

        if (newSettings.alwaysOnTop !== undefined) {
            if (newSettings.alwaysOnTop) {
                // 设置最高级别的置顶
                mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
                mainWindow.moveTop();
                // 在Windows下使用额外的置顶
                if (process.platform === 'win32') {
                    setTimeout(() => {
                        mainWindow.setAlwaysOnTop(false);
                        mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
                        mainWindow.moveTop();
                    }, 100);
                }
            } else {
                mainWindow.setAlwaysOnTop(false);
            }
        }
    }

    return overlaySettings;
});

// 点击穿透控制
ipcMain.handle('set-click-through', (event, ignore) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        try {
            mainWindow.setIgnoreMouseEvents(!!ignore, { forward: true });
            // 在设置穿透时强化置顶（锁定模式）
            if (ignore && overlaySettings.alwaysOnTop) {
                setTimeout(() => {
                    mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
                    mainWindow.moveTop();
                    // Windows额外置顶强化
                    if (process.platform === 'win32') {
                        mainWindow.setVisibleOnAllWorkspaces(true);
                        mainWindow.setVisibleOnAllWorkspaces(false);
                    }
                }, 50);
            }
        } catch (e) { }
    }
});

// 暂停/恢复置顶功能（用于网卡选择/设置面板等交互）
// 支持两种调用：
// 1) ipcRenderer.invoke('pause-always-on-top', true/false)
// 2) ipcRenderer.invoke('pause-always-on-top', { pause: true, timeoutMs: 10000 })
ipcMain.handle('pause-always-on-top', (event, arg) => {
    if (!mainWindow || mainWindow.isDestroyed()) return;
    try {
        let pause = false;
        let timeoutMs = 0;
        if (typeof arg === 'boolean') {
            pause = arg;
        } else if (arg && typeof arg === 'object') {
            pause = !!arg.pause;
            timeoutMs = Number(arg.timeoutMs || 0);
        }

        if (pause) {
            // 硬暂停+可选超时
            alwaysOnTopHardPaused = true;
            if (timeoutMs > 0) {
                alwaysOnTopPauseUntil = Date.now() + timeoutMs;
            }
            // 立即取消置顶
            mainWindow.setAlwaysOnTop(false);
            console.log('[AOT] 暂停自动置顶，超时(ms):', timeoutMs);
        } else {
            // 只有在没有其他暂停请求时才恢复
            if (alwaysOnTopHardPaused) {
                alwaysOnTopHardPaused = false;
                alwaysOnTopPauseUntil = 0;
                if (overlaySettings.alwaysOnTop) {
                    // 延迟恢复置顶，确保UI操作完成
                    setTimeout(() => {
                        if (!mainWindow || mainWindow.isDestroyed()) return;
                        mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
                        mainWindow.moveTop();
                    }, 200);
                }
                console.log('[AOT] 恢复自动置顶');
            }
        }
    } catch (e) {
        console.error('暂停/恢复置顶功能失败:', e);
    }
});

// 打开全部玩家窗口（1440x968）
ipcMain.handle('open-all-players', async () => {
    const win = new BrowserWindow({
        width: 1440,
        height: 968,
        show: true,
        frame: true,
        transparent: false,
        resizable: true,
        webPreferences: { nodeIntegration: true, contextIsolation: false }
    });
    await win.loadFile('all_players.html');
    win.center();
});

// 打开历史记录详情窗口（1440x768）
ipcMain.handle('open-history-detail', async (event, historyId) => {
    const win = new BrowserWindow({
        width: 771,
        height: 672,
        show: true,
        frame: true,
        transparent: false,
        alwaysOnTop: false,
        resizable: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: false,
            webSecurity: false
        }
    });
    // win.webContents.openDevTools({
    //     mode: 'detach'  // 独立窗口显示，避免被主窗口遮挡
    // });

    // 加载历史详情页面，冗余通过 URL 参数传递历史记录ID，增强可靠性
    await win.loadFile('history_detail.html', { search: `id=${encodeURIComponent(historyId ?? '')}` });

    // 等待页面完全加载后传递历史记录ID
    win.webContents.once('did-finish-load', () => {
        console.log('History detail window loaded, sending ID:', historyId);
        win.webContents.send('load-history-data', historyId);
    });

    win.center();

    // 窗口关闭时的处理
    win.on('closed', () => {
        console.log('History detail window closed');
    });

    return true;
});

// 提供光标位置与窗口位置给渲染进程，实现锁定时仅标题栏可点击
ipcMain.handle('get-cursor-and-window-bounds', () => {
    try {
        const point = screen.getCursorScreenPoint();
        const bounds = mainWindow && !mainWindow.isDestroyed() ? mainWindow.getBounds() : { x: 0, y: 0, width: 0, height: 0 };
        return { point, bounds };
    } catch (e) {
        return { point: { x: -1, y: -1 }, bounds: { x: 0, y: 0, width: 0, height: 0 } };
    }
});

ipcMain.handle('close-app', () => {
    app.quit();
});

ipcMain.handle('minimize-app', () => {
    if (mainWindow) {
        mainWindow.minimize();
    }
});

// 处理快捷键更新请求
ipcMain.handle('update-lock-shortcut', (event, newShortcut) => {
    console.log('收到快捷键更新请求:', newShortcut);
    registerGlobalShortcuts(newShortcut);
});

// 当前注册的锁定快捷键
let currentLockShortcut = 'F8';

// 注册全局快捷键
function registerGlobalShortcuts(lockShortcut = 'F8') {
    try {
        // 先注销所有快捷键
        globalShortcut.unregisterAll();

        // 注册自定义锁定快捷键
        const lockRegistered = globalShortcut.register(lockShortcut, () => {
            console.log(`全局快捷键${lockShortcut}被触发 - 锁定/解锁窗口`);
            if (mainWindow && !mainWindow.isDestroyed()) {
                mainWindow.webContents.send('global-shortcut-lock');
            }
        });

        // 注册Ctrl+Shift+R快捷键 - 清空数据（替代F9）
        const clearDataRegistered = globalShortcut.register('Ctrl+Shift+R', () => {
            console.log('全局快捷键Ctrl+Shift+R被触发 - 清空数据');
            if (mainWindow && !mainWindow.isDestroyed()) {
                mainWindow.webContents.send('global-shortcut-clear-data');
            }
        });

        if (lockRegistered && clearDataRegistered) {
            console.log(`✅ 全局快捷键${lockShortcut}和Ctrl+Shift+R注册成功`);
            currentLockShortcut = lockShortcut;
        } else {
            console.log('❌ 全局快捷键注册失败');
        }
        // 试验性：Ctrl+Shift+V 触发全局聊天发送（Enter -> Ctrl+V -> Enter）
        try {
            globalShortcut.register('Ctrl+Shift+V', () => {
                trySendChatPaste();
            });
        } catch (e) {
            console.error('注册Ctrl+Shift+V失败:', e.message);
        }
    } catch (error) {
        console.error('注册全局快捷键时出错:', error);
    }
}

// 应用退出时清理全局快捷键
app.on('will-quit', () => {
    globalShortcut.unregisterAll();
    console.log('全局快捷键已清理');
});

// 尝试在前台窗口发送 Enter -> Ctrl+V -> Enter（需要把游戏置于前台）
function trySendChatPaste() {
    const ps = `$ws = New-Object -ComObject WScript.Shell;` +
        `Start-Sleep -Milliseconds 50;` +
        `$ws.SendKeys('~');` +
        `Start-Sleep -Milliseconds 80;` +
        `$ws.SendKeys('^v');` +
        `Start-Sleep -Milliseconds 80;` +
        `$ws.SendKeys('~');`;
    exec(`powershell -NoProfile -WindowStyle Hidden -Command "${ps}"`, (err) => {
        if (err) console.error('发送聊天按键失败:', err.message);
    });
}

// 渲染进程主动调用：复制后尝试自动发送
ipcMain.handle('simulate-chat-send', async () => {
    trySendChatPaste();
    return { ok: true };
});
